package app

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	_ "github.com/lib/pq"
)

//var DatabaseOrm orm.Ormer

//初始化数据连接
func InitDatabase() {
	//orm.DefaultTimeLoc = time.UTC
	//读取配置文件，设置数据库参数
	//数据库类别
	dbType := NacosConfig.String("db_type")
	//连接名称
	dbAlias := NacosConfig.String(dbType + "::db_alias")
	//数据库名称
	dbName := NacosConfig.String(dbType + "::db_name")
	//数据库连接用户名
	dbUser := NacosConfig.String(dbType + "::db_user")
	//数据库连接用户名
	dbPwd := NacosConfig.String(dbType + "::db_pwd")
	//数据库IP（域名）
	dbHost := NacosConfig.String(dbType + "::db_host")
	//数据库端口
	dbPort := NacosConfig.String(dbType + "::db_port")
	switch dbType {
	case "sqlite3":
		_ = orm.RegisterDataBase(dbAlias, dbType, dbName)
	case "mysql":
		//数据库字符集
		dbCharset := NacosConfig.String(dbType + "::db_charset")
		_ = orm.RegisterDataBase(dbAlias, dbType, dbUser+":"+dbPwd+"@tcp("+dbHost+":"+
			dbPort+")/"+dbName+"?charset="+dbCharset+"&loc=Asia%2FShanghai", 30)
	case "postgres":
		_ = orm.RegisterDriver("postgres", orm.DRPostgres) // 注册驱动
		_ = orm.RegisterDataBase(dbAlias, dbType,
			"user="+dbUser+" password="+dbPwd+" dbname="+dbName+" host="+dbHost+" port="+dbPort+" sslmode=disable",
			30)
	}
	//如果是开发模式，则显示命令信息
	isDev := (beego.AppConfig.String("runmode") == "dev")
	//自动建表
	//_ = orm.RunSyncdb("default", false, isDev)
	if isDev {
		orm.Debug = isDev
	}

	// 初始化orm对象,全局对象、可以在任何对方使用事务
	//DatabaseOrm = orm.NewOrm()
}
